package com.milhouz.findmydroid.view;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.milhouz.findmydroid.R;
import com.milhouz.findmydroid.bean.Character;
import com.milhouz.findmydroid.db.AppDbAPI;

public class CustomCharsAdapter extends ArrayAdapter<Character> {

	public CustomCharsAdapter(Activity parentActivity, List<Character> characters) {
		super(parentActivity.getApplicationContext(), R.layout.menu_item, characters);
	}

	public void updateItem(Character character) {
		add(character);
		notifyDataSetChanged();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		Character character = getItem(position);
		if (character != null) {
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.customchars_item, null);
			}

			TextView labelChar = (TextView) v.findViewById(R.id.labelChar);
			ImageView deleteImg = (ImageView) v.findViewById(R.id.deleteImg);
			labelChar.setText(character.getName());
			deleteImg.setClickable(true);
			deleteImg.setOnClickListener(new DeleteClickListener(position));
		}
		return v;
	}

	class DeleteClickListener implements View.OnClickListener {

		private final int position;

		public DeleteClickListener(final int position) {
			this.position = position;
		}

		@Override
		public void onClick(View v) {
			AppDbAPI.getInstance().deleteCharacter(getContext(), getItem(position).getName());
			remove(getItem(position));
			notifyDataSetChanged();
		}
	}

}
